package com.eascs.banknet.boc.service.trans;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.jdom.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.dao.BOC006Dao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.boc006.BOC006Element;
import com.eascs.banknet.boc.vo.boc006.BOC006Root;
import com.eascs.banknet.common.entity.PrePaymentAmountEntity;
import com.eascs.banknet.common.utils.XmlHelp;
import com.eascs.banknet.constant.EAContant;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;

/**
 * 查询提前还款金额
 * @author Administrator
 *
 */
@Service("boc006Service")
public class BOC006Service extends BOCAbstractService{
	private static final Logger logger = LoggerFactory.getLogger(BOC006Service.class);
	
	@Autowired
	private BOC006Dao boc006Dao;
	
	private String startId;
	
	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("006");
		logEntity.setTypeName("查询提前还款金额");
		logEntity.setStartTime(new Date());
		return logEntity;
	}

	@Override
	public Map<String, String> dowork() {
		String loanapplyNo = "";
		String id = "";	
		LogEntity logEntity = initLogData();
		try {
			logger.info("查询提前还款金额，startId:[{}]", startId);
			
			/**
			 * 查询数据，组装请求xml
			 */
			BOC006Root root = new BOC006Root();
			List<BOC006Element> elementList = boc006Dao.queryData(startId);
			if(elementList.isEmpty()){
				startId = null;
				logger.info("征信调查,没有符合条件的数据");
				return null;
			}
			id = elementList.get(0).getAPPNO();
			loanapplyNo = loanapplyDao.getLoanapplyNoByAppno(id);
			startId = id;	
			root.getBody().setList(elementList);
			//保存xml文件到ftp服务器
			String xml = XmlHelp.convertToXml(root);
			XmlHelp.createXml("006" + "(" + loanapplyNo + ")", loanapplyNo + "&" + xml, "BOC006RQ", bocUtil.getEaFtpInfo());
			
			/*
			 * 调用中行接口
			 */
			logger.info("组装请求数据完成，开始调用中行006接口, appno:[{}], xml:{}", id, xml);
			//加密XML信息
			String returnXml = bocNetService.executeSocket(bocUtil.getBocSocketInfo(),  "006", null, xml);
			if(StringUtil.isEmpty(returnXml)){
				logger.error("中行006接口返回数据为空！");
				throw new Exception("中行S01接口返回数据为空");
			}
			logger.info("中行006接口返回xml完成, returnXml：{}", returnXml);
			
			/*
			 * 解析返回xml，保存数据
			 */
			XmlHelp.createXml("006"+"("+loanapplyNo+")",returnXml,"BOC006RS", bocUtil.getEaFtpInfo());	
			Element rsRoot = XmlHelp.getRootByString(returnXml);
			Element head = rsRoot.getChild("HEADER");
			Element body = rsRoot.getChild("BODY");
			String trncod_rs = head.getChildText("RETCODE")==null?"":head.getChildText("RETCODE");
			if (!EAContant.BOC001RS.equals(trncod_rs.toLowerCase())) {
				throw new Exception(head.getChildText("NOTE"));
			}
			Element trn = body.getChild("OUTPUT");
			Element loanInfo = trn.getChild("LOANINFO");
			String appno = loanInfo.getChildText("APPNO"); 
			String acctnewIn = loanInfo.getChildText("ACCTNEW_IN"); 
			String unduecorbal = loanInfo.getChildText("UNDUECORBAL"); 
			String principal = loanInfo.getChildText("PRINCIPAL"); 
			String intrece = loanInfo.getChildText("INTRECE"); 
			String arrearpia = loanInfo.getChildText("ARREARPIA"); 
			String arrearipia = loanInfo.getChildText("ARREARIPIA"); 
			String totbalarr = loanInfo.getChildText("TOTBALARR"); 
			String totbal = loanInfo.getChildText("TOTBAL"); 
			String accrual = loanInfo.getChildText("ACCRUAL"); 
			String pia = loanInfo.getChildText("PIA"); 
			String iia = loanInfo.getChildText("IIA"); 
			String ipia = loanInfo.getChildText("IPIA"); 
			String totaccr = loanInfo.getChildText("TOTACCR"); 
			String trandate = loanInfo.getChildText("TRANDATE");
			String trantime = loanInfo.getChildText("TRANTIME"); 
			PrePaymentAmountEntity paymentEntity = new PrePaymentAmountEntity();
			paymentEntity.setAppno(appno);
			paymentEntity.setAcctnewIn(acctnewIn);
			paymentEntity.setUnduecorbal(new BigDecimal(unduecorbal));
			paymentEntity.setPrincipal(new BigDecimal(principal));
			paymentEntity.setIntrece(new BigDecimal(intrece));
			paymentEntity.setArrearpia(new BigDecimal(arrearpia));
			paymentEntity.setArrearipia(new BigDecimal(arrearipia));
			paymentEntity.setTotbalarr(new BigDecimal(totbalarr));
			paymentEntity.setTotbal(new BigDecimal(totbal));
			paymentEntity.setAccrual(new BigDecimal(accrual));
			paymentEntity.setPia(new BigDecimal(pia));
			paymentEntity.setIia(new BigDecimal(iia));
			paymentEntity.setIpia(new BigDecimal(ipia));
			paymentEntity.setTotaccr(new BigDecimal(totaccr));
			String trantt = trantime.substring(0,4)+"-"+trantime.substring(4,6)+"-"+trantime.substring(6,8);
			paymentEntity.setTrandate(DateUtils.formateStandDate(trantt));
			//将中行接口返回的数据反写
			int rw = boc006Dao.insert(paymentEntity);
			if(rw <= 0){
				throw new Exception("更新中行BOC006接口结果失败");
			}
			logger.info("征信调查调用成功,id：[{}],appno:[{}]", id, appno);
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_SUCCESS, null);
		} catch (Exception e) {
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR, e.getMessage());
			logger.error("征信调查出现异常，loanapplyNo:[{}], id：[{}]，errMsg：[{}]", loanapplyNo, id, e);
			e.printStackTrace();
		} 
		return null;
	}
}
